/**
 * 
 */
package com.xxl.job.admin.core.open.dingtalk;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import java.util.List;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.collect.ImmutableMap;
import com.xxl.job.admin.core.util.JacksonUtil;

/**
 * 描述：
 * 
 * @author qizai
 * @version: 0.0.1 2021年6月24日-上午11:14:57
 *
 */
public class DingtalkRobotClient {
	private static final Logger	log			= LoggerFactory.getLogger(DingtalkRobotClient.class);
	private static String		ROBOT_URL	= "https://oapi.dingtalk.com/robot/send";
	private static String		HmacSHA256	= "HmacSHA256";

	private static final String signParams(String secret) {
		Long timestamp = System.currentTimeMillis();
		String stringToSign = timestamp + "\n" + secret;
		Mac mac;
		try {
			mac = Mac.getInstance(HmacSHA256);
			mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), HmacSHA256));
			byte[] signData = mac.doFinal(stringToSign.getBytes(StandardCharsets.UTF_8));
			return "&sign=" + WebUtils.encode(Base64.getEncoder().encodeToString(signData)) + "&timestamp="
					+ timestamp;
		} catch (NoSuchAlgorithmException | InvalidKeyException e) {
		}
		return null;
	}

	public static String toJSON(Object obj) {
		return JacksonUtil.writeValueAsString(obj);
	}

	public static RobotSendRequest buildMarkdown(String title, String content) {
		RobotSendRequest request = new RobotSendRequest();
		request.setMsgtype("markdown");
		request.setMarkdown(toJSON(ImmutableMap.of("title", title, "text", content)));
		return request;
	}

	public static RobotSendRequest buildText(String text) {
		RobotSendRequest request = new RobotSendRequest();
		request.setMsgtype("text");
		request.setText(toJSON(ImmutableMap.of("content", text)));
		return request;
	}

	/**
	 * 添加@对象
	 * 
	 * @param robotSendRequest
	 * @param atMobiles
	 * @param atUserIds
	 * @param isAtAll
	 */
	public static void at(RobotSendRequest robotSendRequest, List<String> atMobiles, List<String> atUserIds,
			boolean isAtAll) {
		robotSendRequest
				.setAt(toJSON(ImmutableMap.of("atMobiles", atMobiles, "atUserIds", atUserIds, "isAtAll", isAtAll)));
	}

	/**
	 * 发送markdown消息
	 * 
	 * @param access_token
	 * @param secret
	 * @param title
	 * @param content
	 * @return
	 */
	public static final RobotSendResponse sendMarkdown(String access_token, String secret, String title,
			String content) {
		return send(access_token, secret, buildMarkdown(title, content));
	}

	/**
	 * 发送text消息
	 * 
	 * @param access_token
	 * @param secret
	 * @param text
	 * @return
	 */
	public static final RobotSendResponse sendText(String access_token, String secret, String text) {
		return send(access_token, secret, buildText(text));
	}

	public static final RobotSendResponse send(String access_token, String secret, RobotSendRequest robotSendRequest) {
		String url = ROBOT_URL + "?access_token=" + access_token + signParams(secret);
		try {
			 String json = WebUtils.doPostJSON(url,JacksonUtil.writeValueAsBytes(robotSendRequest));
			log.info("[DingtalkRobot] RobotSendRequest : {}", robotSendRequest);
			log.info("[DingtalkRobot] RobotSendResponse : {}", json);
			RobotSendResponse response = JacksonUtil.readValue(json, RobotSendResponse.class);
			return response;
		} catch (IOException e) {
			throw new IllegalStateException(e);
		}
	}
}
